package com.example.mannortycoon.controller;

import com.example.mannortycoon.entity.SysMenuEntity;
import com.example.mannortycoon.service.ShiroService;
import com.example.mannortycoon.service.SysMenuService;
import com.example.mannortycoon.service.SysUserTokenService;
import com.example.mannortycoon.uitl.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@ApiIgnore
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController{

    private final SysMenuService sysMenuService;

    private final SysUserTokenService sysUserTokenService;

    private final ShiroService shiroService;

    public SysMenuController(SysMenuService sysMenuService,SysUserTokenService sysUserTokenService,ShiroService shiroService){
        this.sysMenuService = sysMenuService;
        this.sysUserTokenService = sysUserTokenService;
        this.shiroService = shiroService;
    }


    /**
     * 获取导航菜单
     */
    @GetMapping("/nav")
    public R nav(HttpServletRequest request){
        String token = request.getHeader("token");
        Long id = sysUserTokenService.getUserIdByToken(token);
        if(id == null){
            return R.error(401,"token不存在或已失效");
        }
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(id);
        Set<String> permissions = shiroService.getUserPermissions(id);
        return R.ok().put("menuList", menuList).put("permissions", permissions);
    }

    /**
     * 所有菜单列表
     */
    @GetMapping("/list")
    public List<SysMenuEntity> list(){
        List<SysMenuEntity> menuList = sysMenuService.list();
        HashMap<Long, SysMenuEntity> menuMap = new HashMap<>(12);
        for (SysMenuEntity s : menuList) {
            menuMap.put(s.getMenuId(), s);
        }
        for (SysMenuEntity s : menuList) {
            SysMenuEntity parent = menuMap.get(s.getParentId());
            if (Objects.nonNull(parent)) {
                s.setParentName(parent.getName());
            }

        }
        return menuList;
    }
}
